package com.skyjing.askit.view.menuviewItem

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Handler
import android.os.Message
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatImageView
import com.skyjing.askit.R
import java.lang.ref.WeakReference
import java.util.*

class MenuViewItem : AppCompatImageView {
    private var mWidth = -1
    private var mHeight = -1
    private var bitmap: Bitmap? = null
    private var mode: MenuViewMode? = null
    private var listen: OnCustomTouch? = null
    private var longPressSpec = 0
    private var isLong = false

    //计时器
    private var count: Long = -1

    //长按过程中事件执行定时器
    private var timer: Timer? = null
    fun setPressBitmap(pressBitmap: Bitmap?) {
        this.pressBitmap = pressBitmap
    }

    fun setNormalBitmap(normalBitmap: Bitmap?) {
        this.normalBitmap = normalBitmap
        setImageBitmap(normalBitmap)
    }

    fun beClick() {
        if (listen != null) {
            listen!!.click(mode)
        }
    }

    //控件被按下时所需替换图片
    private var pressBitmap: Bitmap? = null

    //控件默认设置图片
    private var normalBitmap: Bitmap? = null

    private class MyHandler internal constructor(menuViewItem: MenuViewItem) :
        Handler() {
        var reference: WeakReference<MenuViewItem>
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val item = reference.get()
            when (msg.what) {
                0 -> {
                    if (!item!!.isLong) {
                        return
                    }
                    //700ms时间点需要发送数据
                    if (item.listen != null) {
                        item.listen!!.longPressPoint(item.mode)
                    }
                    if (item.timer == null) {
                        item.timer = Timer()
                    }
                    item.timer!!.schedule(object : TimerTask() {
                        override fun run() {
                            if (item.listen != null) {
                                item.listen!!.keepPress(item.mode)
                            }
                        }
                    }, item.longPressSpec.toLong(), item.longPressSpec.toLong())
                }
            }
        }

        init {
            reference =
                WeakReference(
                    menuViewItem
                )
        }
    }

    private var mHandler: Handler? =
        MyHandler(this)

    constructor(context: Context?) : super(context) {}
    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyle: Int
    ) : super(context, attrs, defStyle) {
    }

    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : super(context, attrs) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.press_img)
        pressBitmap = BitmapFactory.decodeResource(
            resources,
            ta.getResourceId(R.styleable.press_img_press_res, 0)
        )
        normalBitmap = BitmapFactory.decodeResource(
            resources,
            ta.getResourceId(R.styleable.press_img_normal_res, 0)
        )
        ta.recycle()
        if (normalBitmap != null) {
            setImageBitmap(normalBitmap)
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        if (timer != null) {
            timer = null
        }
        mHandler!!.removeMessages(0)
        mHandler = null
        pressBitmap!!.recycle()
        normalBitmap!!.recycle()
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val action = event.action
        when (action) {
            MotionEvent.ACTION_DOWN -> {
                if (!isInView(event.x, event.y)) {
                    return false
                }
                //                Log.e("TAG", "ACTION_DOWN: ");
                if (pressBitmap != null) {
                    setImageBitmap(pressBitmap)
                }
                if (!mHandler!!.hasMessages(0)) {
                    mHandler!!.sendEmptyMessageDelayed(0, 720)
                    count = System.currentTimeMillis()
                }
            }
            MotionEvent.ACTION_UP -> {
                setImageBitmap(normalBitmap)
                if (System.currentTimeMillis() - count <= 700) {
                    mHandler!!.removeMessages(0)
                    if (listen != null) {
                        listen!!.click(mode)
                    }
                } else {
                    //取消长按定时回调
                    if (timer != null) {
                        timer!!.cancel()
                        timer!!.purge()
                        timer = null
                    }
                    if (listen != null) {
                        if (!isLong) {
                            listen!!.click(mode)
                        } else {
                            listen!!.longPressUp(mode)
                        }
                    }
                }
                count = -1
            }
        }
        return true
    }

    /**
     * 自定义长按短按接口
     */
    interface OnCustomTouch {
        /**
         * 短按抬手回调
         *
         * @param mode 控件标签
         */
        fun click(mode: MenuViewMode?)

        /**
         * 长按时间点回调
         *
         * @param mode 控件标签
         */
        fun longPressPoint(mode: MenuViewMode?)

        /**
         * 长按抬手回调
         *
         * @param mode 控件标签
         */
        fun longPressUp(mode: MenuViewMode?)

        /**
         * 连按回调
         *
         * @param mode 控件标签
         */
        fun keepPress(mode: MenuViewMode?)
    }

    /**
     * 点击回调接口
     *
     * @param listen        长按短按回调接口
     * @param longPressSpec 长按事件回调时间间隔
     * @param mode          控件标签
     */
    fun setOnCostomTouch(
        listen: OnCustomTouch?,
        longPressSpec: Int,
        mode: MenuViewMode
    ) {
        this.listen = listen
        isLong = mode.isLong
        this.longPressSpec = longPressSpec
        this.mode = mode
    }

    /**
     * @param x 触摸的x坐标
     * @param y 触摸的y坐标
     * @return 是否在当前view中
     */
    private fun isInView(x: Float, y: Float): Boolean {
        if (mWidth == -1 || mHeight == -1) {
            bitmap = normalBitmap
            mWidth = width
            mHeight = height
        }
        if (null == bitmap || x < 0 || y < 0 || x >= mWidth || y >= mHeight) {
            return false
        }
        //控件中心点的x y坐标
        val centerX = mWidth / 2
        val centerY = mHeight / 2
        //图片位于控件左上角的x y坐标
        val bitmapLeftTopX = centerX - bitmap!!.width / 2
        val bitmapLeftTopY = centerY - bitmap!!.height / 2
        //图片位于控件右下角的x y坐标
        val bitmapRightBottomX = centerX + bitmap!!.width / 2
        val bitmapRightBottomY = centerY + bitmap!!.height / 2
        if (x <= bitmapLeftTopX || x >= bitmapRightBottomX || y <= bitmapLeftTopY || y >= bitmapRightBottomY) {
            return false
        }
        val xb = x / mWidth
        val yb = y / mHeight
        val pixel =
            bitmap!!.getPixel((bitmap!!.width * xb).toInt(), (bitmap!!.height * yb).toInt())
        return Color.TRANSPARENT != pixel
    }
}